package com.dries.chat.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dries.chat.entity.Room;
import com.dries.chat.entity.RoomUser;
import com.dries.chat.form.AddChatRoomForm;
import com.dries.chat.form.JoinChatRoomForm;
import com.dries.chat.mapper.RoomMapper;
import com.dries.chat.mapper.RoomUserMapper;
import com.dries.chat.service.IRoomService;
import com.dries.common.exception.ApiException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements IRoomService {

    @Resource
    private RoomUserMapper roomUserMapper;

    /**
     * 创建聊天室
     *
     * @param addChatRoomForm
     */
    @Transactional
    @Override
    public int createChatRoom(AddChatRoomForm addChatRoomForm) {

        // 1.创建聊天室
        Room room = new Room();
        room.setCreateor(addChatRoomForm.getUserId());
        room.setName(addChatRoomForm.getName());
        room.setAnnouncment(addChatRoomForm.getAnnouncment());

        int insert = baseMapper.insert(room);
        if (insert == 1){
            // 2.房主信息加入到聊天室
            RoomUser roomUser = new RoomUser();
            roomUser.setRoomid(room.getRoomid());
            roomUser.setUserid(addChatRoomForm.getUserId());
            roomUser.setOpt(0);
            return roomUserMapper.insert(roomUser);
        } else {
            throw new ApiException("创建聊天室失败，请稍后再试");
        }

    }

    /**
     * 加入聊天室
     *
     * @param form
     */
    @Transactional
    @Override
    public int joinChat(JoinChatRoomForm form) {

        RoomUser roomUser = new RoomUser();
        roomUser.setUserid(Long.valueOf(form.getUserId()));
        roomUser.setRoomid(Long.valueOf(form.getRoomId()));

        return roomUserMapper.insert(roomUser);
    }
}